package persistent

import "gorm.io/gorm"

func ReviewerTaskView(db *gorm.DB) *gorm.DB {
	return db.Table("node_reviewer_task").
		Joins("LEFT JOIN node ON node_reviewer_task.node_id = node.id").
		Joins("LEFT JOIN workflow ON node.workflow_id = workflow.id")
}

func WorkflowView(db *gorm.DB) *gorm.DB {
	return db.Table("workflow").
		Joins("LEFT JOIN workflow_template ON workflow.workflow_template_id = workflow_template.id").
		Joins("LEFT JOIN node ON workflow.current_node_id = node.id").
		Joins("LEFT JOIN node_template ON node.node_template_id = node_template.id")
}

func NodeReviewerTaskView(db *gorm.DB) *gorm.DB {
	return db.Table("node_reviewer_task").
		Joins("LEFT JOIN node ON node_reviewer_task.node_id = node.id").
		Joins("LEFT JOIN node_template ON node.node_template_id = node_template.id").
		Joins("LEFT JOIN workflow ON node.workflow_id = workflow.id").
		Joins("LEFT JOIN workflow_template ON workflow.workflow_template_id = workflow_template.id")
}

// TimeoutNodesView 超时节点查询视图
// 用于查询所有可能超时的节点及其相关信息
// 包含节点、工作流、工作流模板的关联信息
func TimeoutNodesView(db *gorm.DB) *gorm.DB {
	return db.Table("node").
		Joins("INNER JOIN workflow ON node.workflow_id = workflow.id").
		Joins("INNER JOIN workflow_template ON workflow.workflow_template_id = workflow_template.id")
}

// TimeoutNodesWithTasksView 超时节点及审批任务查询视图
// 用于一次性查询超时节点及其相关的审批任务信息，避免N+1查询问题
// 包含节点、工作流、工作流模板、审批任务的关联信息
func TimeoutNodesWithTasksView(db *gorm.DB) *gorm.DB {
	return db.Table("node").
		Joins("INNER JOIN workflow ON node.workflow_id = workflow.id").
		Joins("INNER JOIN workflow_template ON workflow.workflow_template_id = workflow_template.id").
		Joins("INNER JOIN node_reviewer_task ON node.id = node_reviewer_task.node_id")
}
